<template>
	<!-- 首页/发布页 -->
	<view class="release">
		<!-- 自定义导航栏 -->
		<u-navbar :autoBack="true" placeholder></u-navbar>

		<view class="wrap-card">
			<!-- 标题输入 -->
			<view class="my-20">
				<view class="text-gray-500 mb-10">帖子标题</view>
				<u-input v-model="title" placeholder="请输入帖子标题" />
			</view>

			<!-- 文本域 -->
			<view class="text-gray-500 my-20">想说点啥</view>
			<u-textarea v-model="textContent" maxlength="100" height="100"
						placeholder="随便说点儿什么吧..." count confirmType="done"></u-textarea>

			<!-- 分类选择 -->
			<view class="my-20">
				<view class="text-gray-500 mb-10">选择分类</view>
				<picker mode="selector" :range="categoryNames" :value="categoryIndex" @change="onCategoryConfirm">
					<view class="picker">
					    当前选择：{{ selectedCategoryName || "请选择分类" }}
					</view>
				</picker>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-handle">
			<view class="ml-auto mr-20">
				<u-button text="发布" color="linear-gradient(to right, #dcc20b, #01906c)"
						  :customStyle="{width:'150rpx',height:'60rpx'}" @click="submit"></u-button>
			</view>
		</view>

		<!-- 中间弹出公告栏 -->
		<u-popup :show="popupShow" round="20" mode="center" :customStyle="{width:'80%'}">
			<view class="flex flex-col justify-center items-center m-20">
				<view class="flex justify-center items-center">
					<image class="notice-img" src="/static/img/demo/summer.svg" mode="widthFix"></image>
				</view>
				<view class="flex flex-col my-20">
					<view>严禁发表以下信息：</view>
					<view>1、散布淫秽、色情、赌博、暴力、凶杀、恐怖或者教唆犯罪的信息</view>
					<view>2、侮辱或者诽谤他人，侵害他人合法权益的信息</view>
					<view>3、煽动民族仇恨、民族歧视，破坏民族团结的信息</view>
				</view>
				<u-button :customStyle="btnStyle" :ripple="true" shape="circle" @click="closePopup">朕知道了</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { CategoryApi,PostApi } from '@/api'; // 引入分类接口
import websocketMixin from '@/utils/mixins/websocketMixin';

export default {
	mixins: [websocketMixin],
	data() {
		return {
			isPublished: false, // 是否已经发布
			title: '', // 帖子标题
			textContent: '',
			categoryIndex: 0, // 当前选中分类索引
			categoryList: [], // 所有分类列表
			categoryNames: [], // 仅包含 name 的数组，供 picker 使用
			selectedCategoryName: '', // 当前选中分类名称
			popupShow: true,
			btnStyle: {
				width: "450rpx",
				height: "75rpx",
				background: "linear-gradient(-45deg,#01906c,#34D399)",
				color: "#FFFFFF",
				fontSize: "30rpx"
			},
			draftShow: true
		}
	},
	onLoad() {
		this.fetchCategories().then(() => {
			// 等待分类数据加载完成后再读取草稿
			uni.getStorage({
				key: 'releaseDraft',
				success: (res) => {
					const data = JSON.parse(res.data);
					this.title = data.title || '';
					this.textContent = data.textContent;
					this.selectedCategoryName = data.categoryName || '';
					this.categoryIndex = this.categoryNames.findIndex(item => item === this.selectedCategoryName);
				}
			});
		});
	},
	methods: {
		async fetchCategories() {
			try {
				const res = await CategoryApi.getCategoriesList();
				if (res.code === 200) {
					this.categoryList = res.data;
					this.categoryNames = res.data.map(c => c.name); // 一维数组即可
					if (this.categoryNames.length > 0) {
						this.selectedCategoryName = this.categoryNames[0];
					}
					return Promise.resolve(); // 返回一个 resolved 的 Promise
				}
			} catch (err) {
				console.error('获取分类失败:', err);
				return Promise.reject(err);
			}
		},

		onCategoryConfirm(e) {
			this.categoryIndex = e.detail.value;
			this.selectedCategoryName = this.categoryNames[this.categoryIndex];
		},

		tipDraft() {
			uni.showModal({
				content: "是否要保存为草稿",
				cancelText: "不保存",
				confirmText: "保存",
				success: res => {
					if (res.confirm) this.saveDraft()
					else uni.removeStorage({ key: 'releaseDraft' });
					this.draftShow = false;
					uni.navigateBack();
				}
			});
		},

		saveDraft() {
			uni.setStorage({
				key: 'releaseDraft',
				data: JSON.stringify({
					title: this.title,
					textContent: this.textContent,
					categoryName: this.selectedCategoryName
				})
			});
		},

		async submit() {
			uni.removeStorageSync('releaseDraft'); // 删除草稿
			this.draftShow = false;
			this.isPublished = true; // 标记为已发布
		
			const postData = {
				title: this.title,
				content: this.textContent,
				categoryName: this.selectedCategoryName
			};
		
			console.log("提交的数据：", postData);
		
			try {
				const res = await PostApi.addPost(postData);
				uni.showToast({ title: "发布成功", icon: "success" });
				setTimeout(() => {
					uni.navigateBack();
				}, 1000);
			} catch (err) {
				console.log("发布失败：", err);
				uni.showToast({ title: "发布失败", icon: "error" });
			}
		},

		closePopup() {
			this.popupShow = false;
		}
	},
	onBackPress() {
		if (!this.isPublished && (this.title || (this.textContent && this.draftShow))) {
			this.tipDraft();
			return true;
		}
	}
}
</script>

<style lang="scss" scoped>
.release {
	.notice-img {
		height: 300rpx;
		width: 300rpx;
	}

	.bottom-handle {
		border-top: 1px solid $uni-border-color1;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 85rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
	}
	.picker {
	  padding: 15px;
	  border: 1px solid #ccc;
	  border-radius: 5px;
	}
}
</style>